<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-top"
          size="mini"
          :disabled="!hasSelected || allSelectedOnShelve"
          @click="handleShelve(1)"
          v-hasPermi="['system:product:edit']"
        >上架商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-bottom"
          size="mini"
          :disabled="!hasSelected || allSelectedOffShelve"
          @click="handleShelve(0)"
          v-hasPermi="['system:product:edit']"
        >下架商品</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="productId" />
      <el-table-column label="商品名" align="center" prop="productName" />
      <el-table-column label="商品简介" align="center" prop="productDescription" />
      <el-table-column label="商品图片" align="center" prop="productPhoto">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.productPhoto"
            style="width: 50px; height: 50px"
            :src="scope.row.productPhoto"
            :preview-src-list="[scope.row.productPhoto]"
            fit="cover">
          </el-image>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="商品库存" align="center" prop="productStore" />
      <el-table-column label="商品售卖价" align="center" prop="productSaleprice" />
      <el-table-column label="商品上架状态" align="center" prop="productState">
        <template slot-scope="scope">
          <el-tag :type="scope.row.productState === 1 ? 'success' : 'danger'">
            {{ scope.row.productState === 1 ? '销售中' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品添加时间" align="center" prop="productAddtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productAddtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/system/product"

export default {
  name: "Product",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productDescription: null,
        productPrice: null,
        productSaleprice: null,
        productStore: null,
        productTag: null,
        productState: null,
        productContent: null,
        productCategoryId: null,
        productHref: null,
        productPhoto: null,
        productAddtime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  watch: {
    // 监听路由变化
    '$route'(to, from) {
      if (to.query.refresh) {
        this.getList();  // 刷新商品列表

        // 移除query参数避免重复刷新
        this.$router.replace({
          ...to,
          query: {}
        });
      }
    }
  },
  created() {
    this.getList()
  },
  computed: {
    // 计算是否有选中商品（单选或多选都可以）
    hasSelected() {
      return this.ids.length > 0;
    },
    // 计算是否所有选中商品都已上架
    allSelectedOnShelve() {
      if (this.ids.length === 0) return false;
      return this.productList
        .filter(item => this.ids.includes(item.productId))
        .every(item => item.productState === 1);
    },
    // 计算是否所有选中商品都已下架
    allSelectedOffShelve() {
      if (this.ids.length === 0) return false;
      return this.productList
        .filter(item => this.ids.includes(item.productId))
        .every(item => item.productState === 0);
    }
  },
  methods: {
    /** 查询商品管理列表 */
    getList() {
      this.loading = true
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productName: null,
        productDescription: null,
        productPrice: null,
        productSaleprice: null,
        productStore: null,
        productTag: null,
        productState: null,
        productContent: null,
        productCategoryId: null,
        productHref: null,
        productPhoto: null,
        productAddtime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/snack/product/add');
      this.reset()
      this.open = false
      this.title = "添加商品管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.$router.push({
          path: "/snack/product/add",  // 仍然跳转到 add 路由
          query: { id: productId }     // 但带上商品ID
        });
        this.form = response.data
        this.open = false
        this.title = "修改商品管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 上架/下架操作（支持批量） */
    handleShelve(status) {
      const actionText = status === 1 ? "上架" : "下架";
      const count = this.ids.length;

      this.$modal.confirm(`确定要${actionText}选中的${count}个商品吗？`).then(() => {
        // 批量更新所有选中商品
        const promises = this.ids.map(productId => {
          const currentProduct = this.productList.find(item => item.productId === productId);
          if (!currentProduct) return Promise.resolve();

          const updateData = {
            ...currentProduct,
            productState: status
          };
          return updateProduct(updateData);
        });

        return Promise.all(promises);
      }).then(() => {
        this.$modal.msgSuccess(`成功${actionText}${count}个商品`);
        this.getList(); // 刷新列表
      }).catch(() => {});
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids
      this.$modal.confirm('是否确认删除商品管理编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
